/*
 * 上海远境文化传媒有限公司 版权所有
 */
package controllers.api.v1.base;

import controllers.api.v1.auth.ApiAuth;
import controllers.license.LicenseChecker;
import facade.AppContext;
import facade.base.RoleFacade;
import facade.open.BaseJsonAPI;
import facade.open.request.base.RoleRequest;
import facade.open.response.base.RoleResponse;
import facade.vo.base.RoleBusinessVO;
import facade.vo.base.UserVO;
import models.base.*;
import models.constants.DeletedStatus;
import org.apache.commons.lang.StringUtils;
import play.data.validation.Required;
import play.i18n.Messages;
import play.modules.paginate.JPAExtPaginator;
import play.mvc.With;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色接口.
 */
@With({ApiAuth.class, LicenseChecker.class})
public class RolesAPI extends BaseJsonAPI {


    public static final Integer PAGE_SIZE = 10;

    public static void index(String key, Integer page ,Integer pageSize, String field, String order) {
        Map<String, Object> searchMap = new HashMap<>();
        page = page == null ? 1 : page;
        pageSize = pageSize == null? PAGE_SIZE :pageSize;

        String orderBy = "createdAt desc";
        if(!StringUtils.isEmpty(field)) {
            if (StringUtils.isEmpty(order)) order = "asc";
            orderBy = field+" "+order;
        }

        if (StringUtils.isNotBlank(key))
            searchMap.put("key", "'%" + key + "%'");

        JPAExtPaginator pageList = Role.findByCondition(searchMap, orderBy, page, pageSize);
        renderPaginator(pageList);

    }

    /**
     * 显示详情.
     */
    public static void show(String id) {
        Role role = Role.findOne(id);
        if (role == null)
            renderWarnMessage(403, "角色不存在，可能已经被删除！");
        List<AdminRoleOperate> adminRoleOperateList = AdminRoleOperate.findByRoleId(role.id);
        String[] operateIds = new String[adminRoleOperateList.size()];
        for(int i = 0; i<adminRoleOperateList.size();i++){
            operateIds[i] = adminRoleOperateList.get(i).id+"";
        }
        RoleResponse response = RoleResponse.from(role);
//        List<AdminRoleOperate> roleBusinessList = AdminRoleOperate.loadByRoleId(role.id);
//        response.businessList = roleBusinessList;
        renderData(response);
    }

    /**
     * 为角色保存操作选项
     *
     */
//    public static void saveOperateList() {
//        RoleRequest roleRequest = validateRequestBody("role", RoleRequest.class);
//        Logger.info("----------------------createOperateList coming in -----------------");
//        String[] operateIds = null;
//        Corp corp = AppContext.currentCorp();
//        AdminUser loginUser = AppContext.currentUser();
//        Role role = Role.findByCorpAndId(corp, roleRequest.id);
//        if (role == null){
//            role = RoleFacade.create(roleRequest);
//           // renderWarnMessage(404, Messages.get("warn.no-exists", "角色"));
//        }else{
//            //清空已存在的操作
//            AdminRoleOperate.deleteByRoleId(roleRequest.id);
//        }
//
//        //重新创建选择的操作
//        if (roleRequest.operateIds != null && roleRequest.operateIds.length() > 0) {
//            Date nowTime = new Date();
//             operateIds = roleRequest.operateIds.split(",");
//            for (String businessId : operateIds) {
//                AdminRoleOperate operate = new AdminRoleOperate();
//                operate.role = role;
//                AdminBusiness business = new AdminBusiness();
//                business.id = businessId;
//                operate.business = business;
//                operate.createAt = nowTime;
//                operate.createUser = loginUser;
//                operate.save();
//            }
//        }
//        RoleResponse roleResponse = RoleResponse.from(role,operateIds);
//        flash.put("notice", Messages.get("flash.notice.save-success"));
//        renderData(roleResponse);
//
//    }

    /**
     * 删除角色.
     */
    public static void delete(@Valid @Required String id) {
        Role role = Role.findById(id);
        if (role == null)
            renderWarnMessage(403, Messages.get("warn.no-exists", "角色"));
        Long total = AdminUserRole.countByRole(id);
        if(total>0){
            renderWarnMessage(403, Messages.get("role.delete-with-users", total,role.name));
        }
        role.deleted = DeletedStatus.DELETED ;
        role.modifyAt = new Date();
        role.save();
        flash.put("notice", Messages.get("flash.notice.delete-success", "角色"));
        renderSuccMessage("删除成功！");

    }

    /**
     * 创建新Role.
     */
    public static void create() {
        RoleRequest roleRequest = validateRequestBody("role", RoleRequest.class);
        if(roleRequest == null)
            renderWarnMessage(403, Messages.get("warn.no-exists", "角色"));
        Role role = RoleFacade.create(roleRequest);
        flash.put("notice", Messages.get("flash.notice.save-success"));
        renderData(RoleResponse.from(role));
    }

    /**
     * 编辑Role.
     */
    public static void update(@Valid @Required String id) {
        RoleRequest request = validateRequestBody("role", RoleRequest.class);
        if(request == null){
            renderWarnMessage(403, Messages.get("warn.not-exists","表单参数"));
        }
        Role role = Role.findOne(id);
        if(role == null){
            renderWarnMessage(403, Messages.get("warn.not-exists","角色"));
        }
        notFoundIfNull(role);
        role = RoleFacade.update(role,request);
        flash.put("notice", Messages.get("flash.notice.save-success"));
        renderData(RoleResponse.from(role));
    }

    /**
     * 根据角色查询用户列表
     * @param id 角色ID
     */
    public static void roleUsers(@Valid @Required String id){
        List<UserVO> userList = AdminUser.findByRole(id);
        renderData(userList);
    }

    /**
     * 根据角色查询业务列表
     * @param id 角色ID
     */
    public static void roleBusiness(@Valid @Required String id){
        List<RoleBusinessVO> businessList = AdminBusiness.findByRoleId(id);
        renderData(businessList);
    }

}
